package popup

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import app.AppContext
import com.hontech.kdxclient.R
import manager.AppManager
import manager.TaskManager
import protocol.BaseProtocol
import serialport.DeliverPortManager


class TakeGoodsWindow : Runnable {

    companion object {
        val Instance: TakeGoodsWindow by lazy { TakeGoodsWindow() }

        const val Timeout = 20

        var isShow = false
    }

    private var mCounter = 0

    private val mView = LayoutInflater.from(AppContext).inflate(R.layout.popup_take_count, null)
    private val mWindow = PopupWindow(mView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true)
    private val mTextViewCount = mView.findViewById<TextView>(R.id.id_popup_take_text_view_count)

    override fun run() {
        mCounter --
        mTextViewCount.text = mCounter.toString()
        if (mCounter <= 0) {
            timeout()
            return
        }
        TaskManager.UiHandler.postDelayed(this, 1000)
    }

    private fun timeout() {

        // 关门
        val buf = BaseProtocol(0x01).append7Byte(0x01).build()
        DeliverPortManager.Instance.write(buf)

        TaskManager.UiHandler.postDelayed({
            dismiss()
        }, 5000)
    }

    private fun startCounter() {
        mCounter = Timeout
        mTextViewCount.text = mCounter.toString()
        TaskManager.UiHandler.postDelayed(this, 1000)
    }

    fun dismiss() {
        if (!isShow) {
            return
        }
        isShow = false
        mWindow.dismiss()
        AppManager.isBusy = false
    }

    /**
     *         if (isChecked) {
    val buf = BaseProtocol(0x01).append7Byte(0x00).build()
    DeliverPortManager.Instance.write(buf)
    } else {
    val buf = BaseProtocol(0x01).append7Byte(0x01).build()
    DeliverPortManager.Instance.write(buf)
    }
     */

    fun show(view: View) {
        if (isShow) {
            return
        }
        isShow = true
        AppManager.isBusy = true
        mWindow.showAtLocation(view, Gravity.CENTER, 0, 0)
        startCounter()
        // 开门
        val buf = BaseProtocol(0x01).append7Byte(0x00).build()
        DeliverPortManager.Instance.write(buf)
    }
}
